import { Injectable } from '@angular/core';
import { LoadingController } from 'ionic-angular';
import { ImageViewerController } from 'ionic-img-viewer';
/*
  Generated class for the FilesProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/

/*加载普通js*/
declare let EXIF: any;

@Injectable()
export class FilesProvider {

	constructor(
		public loadingCtrl: LoadingController,
		public imageViewerCtrl: ImageViewerController) {
		console.log('Hello FilesProvider Provider');
	}

	/**
	 * 显示图片
	 */
	public showPicImage(myImage) {
		let imageViewer = this.imageViewerCtrl.create(myImage);
		imageViewer.present();

		//setTimeout(() => imageViewer.dismiss(), 10000);
		//imageViewer.onDidDismiss(() => alert('Viewer dismissed'));
	}

	/**
	 * 上传图片
	 */

	public showPicUpload() {
		let promise = new Promise((success, fail) => {
			//动态创建文件上传控件
			let file: HTMLElement = document.createElement('input');
			file.setAttribute("type", "file");
			file.setAttribute("accept", "image/*");
			file.id = 'showPicUpload_' + new Date().getTime();
			//动态图
			let that = this;
			let loading = this.loadingCtrl.create({
				content: '处理中...'
			});
			file.onchange = function(e) {
				loading.present();
				let files = e.target['files'][0];
				let reader = new FileReader();
				reader.onload = function() {
					//图片压缩
					that.fileCompress(files, this.result).then(val => {
						loading.dismiss();
						if(success)
							success({ 'name': files.type, 'type': files.type, 'data': val });
					}, error => {
						loading.dismiss();
						if(fail)
							fail();
					});
				};
				reader.readAsDataURL(files);
				reader.onerror = function() {
					loading.dismiss();
					if(fail)
						fail();
				};
			};
			document.body.appendChild(file);
			file.click();
		});
		//异步回调
		return promise;
	}

	/**
	 * 图片压缩 (压缩宽度在750以内)
	 */
	public fileCompress(files, base64) {
		let promise = new Promise((success, fail) => {
			//获取照片方向角属性，用户旋转控制
			let that = this;
			EXIF.getData(files, function() {
				EXIF.getAllTags(this);
				let Orientation = EXIF.getTag(this, 'Orientation');
				let snowImg: any = new Image();
				snowImg.src = base64;
				snowImg.onload = function() {
					//设置图片像素
					let maxwidth: any = 400;
					let scale: any = snowImg['width'] / snowImg['height']; //宽高比
					let quality: any = 0.5; // 默认图片质量为0.7
					let width: any = maxwidth;
					let height: any = maxwidth / scale;
					//生成canvas
					let canvas: HTMLCanvasElement = document.createElement('canvas');
					canvas.width = width;
					canvas.height = height;
					let ctx = canvas.getContext('2d');
					ctx.drawImage(snowImg, 0, 0, width, height); //开始画图
					//图片旋转
					if(Orientation != "" && Orientation != 1) {
						switch(Orientation) {
							case 6: //需要顺时针（向左）90度旋转 
								that.rotateImg(snowImg, 'left', canvas);
								break;
							case 8: //需要逆时针（向右）90度旋转 
								that.rotateImg(snowImg, 'right', canvas);
								break;
							case 3: //需要180度旋转 
								that.rotateImg(snowImg, 'right', canvas); //转两次 
								that.rotateImg(snowImg, 'right', canvas);
								break;
						}
					}
					// quality值越小，所绘制出的图像越模糊
					let newbase64 = canvas.toDataURL('image/jpeg', quality);
					if(success)
						success(newbase64);
				};
			});
		});
		//异步回调
		return promise;
	}

	/**
	 * 对图片旋转处理
	 */
	public rotateImg(img, direction, canvas) {
		//最小与最大旋转方向，图片旋转4次后回到原方向   
		let min_step = 0;
		let max_step = 3;
		if(img == null) return;
		//img的高度和宽度不能在img元素隐藏后获取，否则会出错   
		let height = img.height;
		let width = img.width;
		let step = 2;
		if(step == null) {
			step = min_step;
		}
		if(direction == 'right') {
			step++;
			//旋转到原位置，即超过最大值   
			step > max_step && (step = min_step);
		} else {
			step--;
			step < min_step && (step = max_step);
		}
		//旋转角度以弧度值为参数   
		let degree = step * 90 * Math.PI / 180;
		let ctx = canvas.getContext('2d');
		switch(step) {
			case 0:
				canvas.width = width;
				canvas.height = height;
				ctx.drawImage(img, 0, 0);
				break;
			case 1:
				canvas.width = height;
				canvas.height = width;
				ctx.rotate(degree);
				ctx.drawImage(img, 0, -height);
				break;
			case 2:
				canvas.width = width;
				canvas.height = height;
				ctx.rotate(degree);
				ctx.drawImage(img, -width, -height);
				break;
			case 3:
				canvas.width = height;
				canvas.height = width;
				ctx.rotate(degree);
				ctx.drawImage(img, -width, 0);
				break;
		}
	}
}